/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: lishuo
 * Date: 2023-05-09
 * Time: 9:53
 */
public class BlockingQueue {
    private volatile int[] array; // 循环队列
    private volatile int head; // 队头
    private volatile int tail; // 队尾

    // 构造循环队列
    public BlockingQueue(){
        this.array = new int[100];
        this.head = 0;
        this.tail = 0;
    }

    // 队列元素个数
    public int size = 0;

    // 插入元素
    public synchronized void put(int value) throws InterruptedException {
        if (size == array.length) {
            // 队满阻塞
            this.wait();
            return;
        }
        array[tail] = value;
        tail++;
        size++;
        // 循环
        if (tail== array.length) {
            tail=0;
        }
        this.notify();

    }

    // 取出元素
    public synchronized int take() throws InterruptedException {
        if (size ==0) {
            // 队空阻塞
            this.wait();
        }
        int value = array[head];
        head++;
        size--;
        // 循环
        if (head == array.length) {
            head = 0;
        }
        this.notify();
        return value;
    }
}
